<?php
	


class MysqlApi extends ApiBase{
	private static $handle = null;
	private $lastSql = null;
	private static $conf = null;



	
	/**
	 * 构造函数，初始化插件
	 */
	public function __construct() {
		
		parent::__construct();
		
		
		if(is_null(self::$handle)){
			$conf = n_confGet('mysql');
			if(!$conf['state']){
				throw new PException("conf:读取失败");
			}
			self::$conf = $conf['data'];

			// foreach($conf as $key=>$val){
				// self::$handle['db'.$key] = new MysqlDriver($val['host'],$val['user'],$val['pwd'],$val['dbname']);
				// self::$handle['db'.$key]->exec("set names UTF8");
			// }
			
		}

		
	}

	public function __get($key){
		if(isset(self::$handle[$key])){
			return self::$handle[$key];
		}
		
				
		if(!isset(self::$conf[$key])){
			throw new PException("找不到数据库配置:{$key}");
		}
		
		//self::$handle[$key] = new MysqlDriver(self::$conf[$key]);

		self::$handle[$key] = new MysqlDriver(self::$conf[$key]);
		
				
		return self::$handle[$key];
	}

	/**
	 * checkConnect
	 *
	 * 检查mysql的连接是否正常，防止Mysql has gone away
	 * 
	 * @param  string $dbKey   DB名
	 * 
	 * @return object
	 */
	public function checkConnect($dbKey = '') {

		if(empty($dbKey)) {
			$dbKey = 'db001';
		} 
		$dbObject = $this->getDBObjectByKey($dbKey);

		if(is_object($dbObject) && !$dbObject->ping()) {
			$dbObject = $this->reconnect($dbKey);
		}

		return $dbObject;	
	}

	/**
	 * getDBObjectByKey
	 *
	 * 根据DB别名获取mysql连接对象
	 * 
	 * @param  string $dbKey DB别名
	 * 
	 * @return object
	 */
	protected function getDBObjectByKey($dbKey) {
		if(isset(self::$conf[$dbKey])) {
			$dbObject = $this->$dbKey;
		} else {
			$dbObject = $this->cname($dbKey);
		}

		return $dbObject;
	}

	/**
	 * reconnect
	 *
	 * 重新链接DB
	 * 
	 * @param  string $dbKey DB别名
	 * 
	 * @return object
	 */
	public function reconnect($dbKey) {
		if(empty($dbKey)) return false;

		$dbObject = $this->getDBObjectByKey($dbKey);
		//先强制关闭mysql资源
		$dbObject->close();
		unset($dbObject);
		//再删除静态资源
		if(isset(self::$conf[$dbKey])) {
			unset(self::$handle[$dbKey]);
		} else {
			$key = $this->_getCnameKey($dbKey);
			unset(self::$handle[$key]);
		}

		$dbObject = $this->getDBObjectByKey($dbKey);

		return $dbObject;

	}
	private function _getCnameKey($dbName) {
		return 'cname' . $dbName;
	}
	
	public function cname($cname){
		/*$mysql = $this->db001;
		//linruiyan@2014-5-7 增加一个缓存
		static $cache = array();
		if(!isset($cache[$cname])){
			$cache[$cname] = $mysql->fetchFirst("select * from mysql_main where cname='{$cname}'");
		}

		if(empty($cache[$cname])){
			throw new PException("找不到数据库别名:-{$cname}-");
		}

		$server = $cache[$cname]['server'];

		if(isset(self::$handle[$server])){
			self::$handle[$server]->exec("use {$cname}");//切换数据库
			return self::$handle[$server];
		}

		if(!isset(self::$conf[$server])){
			throw new PException("找不到数据库配置:{$server}");
		}*/

		self::$handle[$cname] = new MysqlDriver(self::$conf[$cname]);

		// self::$handle[$cname]->exec("use {$cname}");
		return self::$handle[$cname];
	}

	/**
	 * [arCname 归档库切换]
	 * @param  [object] $db    [数据库连接]
	 * @param  [string] $cname [站点scode]
	 * @return [object]        [description]
	 */
	public function arCname($db,$cname){
		$db->exec("use dms;");
		
		$rs = $db->fetchFirst("select * from mysql_main where cname='{$cname}'");

		if(empty($rs)){
			throw new PException("找不到数据库别名:-{$cname}-");
		}

		$db->exec("use {$cname}");

		return $db;
	}

	public function getCNameInfo($cname) {
		if(empty($cname)) return false;

		$mysql = $this->db001;
		
		$rs = $mysql->fetchFirst("SELECT * FROM mysql_main WHERE cname = '{$cname}'");

		return $rs;
	}
	public function getCnameServer(){
		return self::$conf['cnameserver'];
	}
	public function cnameSave($cname,$server){
		$row = $this->db001->fetchFirst("select * from `mysql_main` where cname='{$cname}'");
		if (empty($row)) {
			$this->db001->insert("mysql_main",array("cname"=>$cname,"server"=>$server));
		}
	}

	/**
	 * [归档库db切换]
	 * @param  [string] $scode [站点scode]
	 * @return [dbObject]      [数据库对象]
	 */
	public function changeArDB($scode){
		$rs = n_api("nsite")->getGcode($scode);
		$gcode = 'content_'.$rs;
		$db = n_api('mysql')->dms_archive;
		return n_api("mysql")->arCname($db,$gcode);
	}

	/*
	*	
	* [创建一个链接]
	*
	*/
	public function RawConnectDb($key) {

		if(empty($key)) return false;

		try{
			self::$handle[$key] = new MysqlDriver(self::$conf[$key]['master']);
		}catch(Exception $e){
			self::$handle[$key] = new MysqlDriver(self::$conf[$key]['slave']);
		}
				
		return self::$handle[$key];
	}
	
	public function __destruct(){
		// foreach(self::$handle as $key=>$val){
			// self::$handle[$key]->debug();
		// }				
	}
}
